//
//  FlutterNativeMapPOIPlugin.m
//  Runner
//
//  Created by mac on 2021/11/29.
//

#import "FlutterNativeMapPOIPlugin.h"
//#import <CoreLocation/CoreLocation.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "MJRefresh.h"
#import "POITableViewCell.h"


/** 设备的宽 */
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
/** 设备的高 */
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

@interface FlutterNativeMapPOIPlugin ()<UISearchControllerDelegate,UISearchResultsUpdating,MAMapViewDelegate,AMapLocationManagerDelegate,AMapSearchDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIViewController *controller;
@property (nonatomic, copy) FlutterResult result;


@property (nonatomic, strong)UISearchController *searchController;
@property (nonatomic, assign)CLLocationCoordinate2D currentLocationCoordinate;
@property (nonatomic, strong)MAMapView * mapView;
@property (nonatomic, strong)AMapLocationManager *locationManager;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic,strong)AMapSearchAPI *mapSearch;
@property (nonatomic,strong)NSArray *dataArray;
@property (nonatomic ,strong)AMapPOIAroundSearchRequest *request; //周边 搜索
@property (nonatomic ,strong)AMapPOIKeywordsSearchRequest *keywordsRequest;//关键字 搜索
@property (nonatomic ,assign)NSInteger currentPage;
@property (nonatomic ,assign)BOOL isSelectedAddress;
@property (nonatomic ,strong)NSIndexPath *selectedIndexPath;
@property (nonatomic ,strong)NSString *city;//定位的当前城市，用于搜索功能

@property (nonatomic ,strong)UITableView *searchTableView;//用于搜索的tableView
@property (nonatomic ,strong)NSArray *tipsArray;//搜索提示的数组
@property (nonatomic ,strong)NSMutableArray *remoteArray;
@property (nonatomic ,strong)AMapPOI *currentPOI;//点击选择的当前的位置插入到数组中
@property (nonatomic ,assign)BOOL isClickPoi;

@property (nonatomic, assign) bool isKeywordSearch;//是否是 关键字搜索 默认 No


@end
//通道名称
static NSString *const CHANNEL_NAME = @"com.ehs2.flutter_albs_map_poi";
//通道方法
static NSString *const CHANNEL_METHOD = @"getCurrentLocation";
// 高德地图 key
static NSString *const GDMAP_KEY = @"76ffe13cd5b5e54de8a438aaec4fc8ca";

@implementation FlutterNativeMapPOIPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:CHANNEL_NAME
            binaryMessenger:[registrar messenger]];


    UIViewController *viewController = [UIApplication sharedApplication].delegate.window.rootViewController;

    FlutterNativeMapPOIPlugin *plugin = [[FlutterNativeMapPOIPlugin alloc]initWithViewController:viewController];
    [AMapLocationManager updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];
    [AMapLocationManager updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];

    [registrar addMethodCallDelegate:plugin channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([CHANNEL_METHOD isEqualToString:call.method]) {


      _result = result;
      [self kInitLocationInfo:call result:result];
  } else {
    result(FlutterMethodNotImplemented);
  }
}
/**
 *初始化定位
 */
- (void)kInitLocationInfo:(FlutterMethodCall*)call result:(FlutterResult)result{

    [AMapServices sharedServices].apiKey = GDMAP_KEY;//call.arguments;
    [self setUpSearchController];


    if (@available(iOS 13.0, *)) {
        self.controller.view.backgroundColor = [UIColor systemGroupedBackgroundColor];
       } else {
           // Fallback on earlier versions
           self.controller.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
       }


    self.currentPage = 1;
    [self initMapView];
    [self.controller.view addSubview:self.tableView];
    [self configLocationManager];


    self.remoteArray = @[].mutableCopy;
    self.mapSearch = [[AMapSearchAPI alloc] init];
    self.mapSearch.delegate = self;

    //关键字搜索
    [self kPOIKeywordsSearchRequest];

    [self kPOIAroundSearchRequest];

    //更字段 判断 是否 要执行

    self.isKeywordSearch = true;
    [self locateAction];

    self.selectedIndexPath=[NSIndexPath indexPathForRow:-1 inSection:-1];
}

// 关键字 搜索
- (void)kPOIKeywordsSearchRequest{

    self.keywordsRequest = [[AMapPOIKeywordsSearchRequest alloc]init];
    

    self.keywordsRequest.city = @"";
    self.keywordsRequest.keywords = @"商务住宅|餐饮服务|生活服务";
//    self.keywordsRequest.types = @"商务住宅|餐饮服务|生活服务";
//    self.keywordsRequest.requireExtension    = YES;

    self.keywordsRequest.cityLimit           = YES;
//    self.keywordsRequest.requireSubPOIs      = YES;

    [self.mapSearch AMapPOIKeywordsSearch:self.keywordsRequest];

//    self.keywordsRequest.location

}

// 周边 搜索
- (void)kPOIAroundSearchRequest{

    self.request = [[AMapPOIAroundSearchRequest alloc] init];
    self.request.keywords  = @"商务住宅|餐饮服务|生活服务";
    /* 按照距离排序. */
    self.request.sortrule = 0;
//    self.request.offset = 50;
//    self.request.requireExtension = YES;

}

- (void)setUpSearchController{
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.delegate = self;
    self.searchController.searchResultsUpdater = self;
    self.searchController.hidesNavigationBarDuringPresentation = NO;


    if (@available(iOS 12.0, *)) {
        self.searchController.obscuresBackgroundDuringPresentation = NO;
    }else{
        self.searchController.dimsBackgroundDuringPresentation = NO;
    }

    UISearchBar *bar = self.searchController.searchBar;
    bar.frame = CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, SCREEN_WIDTH, 44);
    bar.barStyle = UIBarStyleDefault;
    bar.translucent = YES;


    if (@available(iOS 13.0, *)) {

        bar.barTintColor = [UIColor systemGroupedBackgroundColor];

    } else {
           // Fallback on earlier versions
           bar.barTintColor = [UIColor groupTableViewBackgroundColor];

        }

    bar.tintColor = [UIColor colorWithRed:0 green:(190 / 255.0) blue:(12 / 255.0) alpha:1];
    UIImageView *view = [[[bar.subviews objectAtIndex:0] subviews] firstObject];
    view.layer.borderColor = [UIColor colorWithRed:((0xdddddd >> 16) & 0x000000FF)/255.0f green:((0xdddddd >> 8) & 0x000000FF)/255.0f blue:((0xdddddd) & 0x000000FF)/255.0 alpha:1].CGColor;
    view.layer.borderWidth = 0.7;

    bar.showsBookmarkButton = NO;
    UITextField *searchField = [bar valueForKey:@"searchField"];
    searchField.placeholder = @"搜索地点";
    if (searchField) {
        [searchField setBackgroundColor:[UIColor whiteColor]];
        searchField.layer.cornerRadius = 3.0f;
        searchField.layer.borderColor = [UIColor colorWithRed:((0xdddddd >> 16) & 0x000000FF)/255.0f green:((0xdddddd >> 8) & 0x000000FF)/255.0f blue:((0xdddddd) & 0x000000FF)/255.0 alpha:1].CGColor;
        searchField.layer.borderWidth = 0.7;
    }

    [self.controller.view addSubview:bar];
}

- (void)initMapView{
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 64 + 44, SCREEN_WIDTH, 300)];
    self.mapView.delegate = self;
    self.mapView.mapType = MAMapTypeStandard;
    self.mapView.showsScale = NO;
    self.mapView.showsCompass = NO;
    self.mapView.showsUserLocation = YES;
    self.mapView.zoomLevel = 15.0;
    [self.controller.view addSubview:self.mapView];

    UIButton *localButton = [UIButton buttonWithType:UIButtonTypeCustom];
    localButton.backgroundColor = [UIColor redColor];
    localButton.frame = CGRectMake(SCREEN_WIDTH - 60, 240, 50, 50);
    [localButton addTarget:self action:@selector(localButtonAction) forControlEvents:UIControlEventTouchUpInside];
    localButton.layer.cornerRadius = 25;
    localButton.clipsToBounds = YES;
    [localButton setImage:[UIImage imageNamed:@"定位"] forState:UIControlStateNormal];
    [self.mapView addSubview:localButton];

}

- (UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 408, SCREEN_WIDTH, SCREEN_HEIGHT - 408) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];

    }
    return _tableView;
}

- (UITableView *)searchTableView{
    if (_searchTableView == nil) {
        _searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - GK_STATUSBAR_NAVBAR_HEIGHT) style:UITableViewStylePlain];
        _searchTableView.delegate = self;
        _searchTableView.dataSource = self;
        _searchTableView.tableFooterView = [UIView new];
    }
    return _searchTableView;
}

// 定位SDK
- (void)configLocationManager {
    self.locationManager = [[AMapLocationManager alloc] init];
    [self.locationManager setDelegate:self];
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //单次定位超时时间
    [self.locationManager setLocationTimeout:6];
    [self.locationManager setReGeocodeTimeout:3];
}

- (void)locateAction {
//    [self showHudInView:self.controller.view hint:@"正在定位..."];
    //带逆地理的单次定位
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error) {
//            [self showHint:@"定位错误" yOffset:-180];
            NSLog(@"locError:{%ld - %@};",(long)error.code,error.localizedDescription);
            if (error.code == AMapLocationErrorLocateFailed) {
                return ;
            }
        }
        //定位信息
        NSLog(@"location:%@", location);
        if (regeocode)
        {
//            [self hideHud];
            self.isClickPoi = NO;
            self.currentLocationCoordinate = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
            self.city = regeocode.city;
            [self showMapPoint];
            [self setCenterPoint];

            self.request.location = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
            [self.mapSearch AMapPOIAroundSearch:self.request];
        }
    }];

}

- (void)showMapPoint{
    [_mapView setZoomLevel:15.1 animated:YES];
    [_mapView setCenterCoordinate:self.currentLocationCoordinate animated:YES];
}

- (void)setCenterPoint{
    MAPointAnnotation * centerAnnotation = [[MAPointAnnotation alloc] init];//初始化注解对象
    centerAnnotation.coordinate = self.currentLocationCoordinate;//定位经纬度
    centerAnnotation.title = @"";
    centerAnnotation.subtitle = @"";
    [self.mapView addAnnotation:centerAnnotation];//添加注解

}


#pragma mark - MAMapView Delegate
- (MAAnnotationView *)mapView:(MAMapView *)mapView
            viewForAnnotation:(id<MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.canShowCallout= YES;       //设置气泡可以弹出，默认为NO
        annotationView.animatesDrop = YES;        //设置标注动画显示，默认为NO
        annotationView.draggable = YES;        //设置标注可以拖动，默认为NO
        annotationView.pinColor = MAPinAnnotationColorRed;
        return annotationView;
    }
    return nil;
}


- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    [self.mapView removeAnnotations:self.mapView.annotations];

    //地图 移动 将 选中的 重置
    self.selectedIndexPath=[NSIndexPath indexPathForRow:-1 inSection:-1];


    CLLocationCoordinate2D centerCoordinate = mapView.region.center;
    self.currentLocationCoordinate = centerCoordinate;

    MAPointAnnotation * centerAnnotation = [[MAPointAnnotation alloc] init];
    centerAnnotation.coordinate = centerCoordinate;
    centerAnnotation.title = @"";
    centerAnnotation.subtitle = @"";
    [self.mapView addAnnotation:centerAnnotation];
    //主动选择地图上的地点
    if (!self.isSelectedAddress) {
        self.isClickPoi = NO;
        self.isKeywordSearch = NO;
        [self.tableView setContentOffset:CGPointMake(0,0) animated:NO];

//        默认选择 第一个
//        self.selectedIndexPath=[NSIndexPath indexPathForRow:0 inSection:0];
        self.request.location = [AMapGeoPoint locationWithLatitude:centerCoordinate.latitude longitude:centerCoordinate.longitude];
        self.currentPage = 1;
        self.request.page = self.currentPage;

        //周边搜索
        [self.mapSearch AMapPOIAroundSearch:self.request];
    }
    self.isSelectedAddress = NO;

}


#pragma mark -AMapSearchDelegate
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    NSMutableArray *remoteArray = response.pois.mutableCopy;
    self.remoteArray = remoteArray;
    if (self.isClickPoi) {
        [remoteArray insertObject:self.currentPOI atIndex:0];
    }
    if (self.currentPage == 1) {
        self.dataArray = remoteArray;


        if (self.dataArray.count>0) {


            if (self.isKeywordSearch) {



                AMapPOI *POIModel = self.dataArray[0];

                CLLocationCoordinate2D locationCoordinate = CLLocationCoordinate2DMake(POIModel.location.latitude, POIModel.location.longitude);
                [_mapView setCenterCoordinate:locationCoordinate animated:YES];

            }




        }







    }else{
        NSMutableArray * moreArray = self.dataArray.mutableCopy;
        [moreArray addObjectsFromArray:remoteArray];
        self.dataArray = moreArray.copy;
    }

    [self.tableView reloadData];


}

- (void)onInputTipsSearchDone:(AMapInputTipsSearchRequest *)request response:(AMapInputTipsSearchResponse *)response{

    self.tipsArray = response.tips;
    [self.searchTableView reloadData];

}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.tableView) {
        return self.dataArray.count;
    }else{
        return self.tipsArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"POITableViewCell";
    POITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:cellID owner:nil options:nil] firstObject];
    }
    if (tableView == self.tableView) {
        AMapPOI *POIModel = self.dataArray[indexPath.row];
        cell.nameLabel.text = POIModel.name;
        cell.addressLable.text = POIModel.address;

        if (indexPath.row==self.selectedIndexPath.row){
            NSLog(@"%ld",(long)indexPath.row);
            NSLog(@"%ld",(long)self.selectedIndexPath.row);

            cell.accessoryType=UITableViewCellAccessoryCheckmark;
        }else{
            cell.accessoryType=UITableViewCellAccessoryNone;
        }
    }else{
        AMapTip *tipModel = self.tipsArray[indexPath.row];
        cell.nameLabel.text = tipModel.name;
        cell.addressLable.text = tipModel.address;

    }

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.tableView == tableView) {
        self.selectedIndexPath=indexPath;
        [tableView reloadData];
        AMapPOI *POIModel = self.dataArray[indexPath.row];
        CLLocationCoordinate2D locationCoordinate = CLLocationCoordinate2DMake(POIModel.location.latitude, POIModel.location.longitude);
        [_mapView setCenterCoordinate:locationCoordinate animated:YES];
        self.isSelectedAddress = YES;
        self.isKeywordSearch = NO;



        // 获取得到的地理信息
        NSMutableDictionary *resultDic = [[NSMutableDictionary alloc]init];
        resultDic[@"province"] = POIModel.province;//省
        resultDic[@"city"] = POIModel.city;//市
        resultDic[@"ad"] = POIModel.district;//行政区
        resultDic[@"snippet"] = POIModel.address;//地址信息
        resultDic[@"title"] = POIModel.name;//名称

        resultDic[@"lng"] = [NSString stringWithFormat:@"%f",POIModel.location.longitude];//经度
        resultDic[@"lat"] = [NSString stringWithFormat:@"%f",POIModel.location.latitude];//纬度


        NSLog(@"%@", resultDic);

    }else{
        self.searchController.active = NO;

        if (@available(iOS 13.0, *)) {
            UIWindow *window = nil;
            for (UIWindowScene *windowScene in [UIApplication sharedApplication].connectedScenes) {

                if (windowScene.activationState == UISceneActivationStateForegroundActive) {

                    window = windowScene.windows.firstObject;

                    break;

                }
            }
            [window endEditing:YES];
        } else {
            [[[UIApplication sharedApplication] keyWindow] endEditing:YES];

        }




        AMapTip *tipModel = self.tipsArray[indexPath.row];
        CLLocationCoordinate2D locationCoordinate = CLLocationCoordinate2DMake(tipModel.location.latitude, tipModel.location.longitude);
        [_mapView setCenterCoordinate:locationCoordinate animated:YES];

        self.isKeywordSearch = NO;

//默认选择第一个
//        self.selectedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView reloadData];

        AMapPOI *POIModel = [AMapPOI new];
        POIModel.address = [NSString stringWithFormat:@"%@%@",tipModel.district,tipModel.address];
        POIModel.location = tipModel.location;
        POIModel.name = tipModel.name;
        self.currentPOI = POIModel;
        self.isClickPoi = YES;
        [self.tableView reloadData];


    }


}

//  地图的代理
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.searchTableView) {
        if (@available(iOS 13.0, *)) {
            UIWindow *window = nil;
            for (UIWindowScene *windowScene in [UIApplication sharedApplication].connectedScenes) {

                if (windowScene.activationState == UISceneActivationStateForegroundActive) {

                    window = windowScene.windows.firstObject;

                    break;

                }
            }
            [window endEditing:YES];
        } else {
            [[[UIApplication sharedApplication] keyWindow] endEditing:YES];

        }
    }
}
#pragma mark - UISearchControllerDelegate && UISearchResultsUpdating

//谓词搜索过滤
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    if (searchController.searchBar.text.length == 0) {
        return;
    }
    [self.controller.view addSubview:self.searchTableView];
    AMapInputTipsSearchRequest *tips = [[AMapInputTipsSearchRequest alloc] init];
    tips.keywords = searchController.searchBar.text;
    tips.city = self.city;
    [self.mapSearch AMapInputTipsSearch:tips];

}


#pragma mark - UISearchControllerDelegate代理
- (void)willPresentSearchController:(UISearchController *)searchController{
    self.searchController.searchBar.frame = CGRectMake(0, 0, self.searchController.searchBar.frame.size.width, 44.0);
    self.mapView.frame = CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, SCREEN_WIDTH, 300);
//    self.tableView.frame = CGRectMake(0, 364, SCREEN_WIDTH, SCREEN_HEIGHT - 364);
    NSLog(@"ss---%@",NSStringFromCGRect(self.tableView.frame));

}

- (void)didDismissSearchController:(UISearchController *)searchController{
    self.searchController.searchBar.frame = CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, self.searchController.searchBar.frame.size.width, 44.0);
    self.mapView.frame = CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT + 44, SCREEN_WIDTH, 300);
//    self.tableView.frame = CGRectMake(0, 408, SCREEN_WIDTH, SCREEN_HEIGHT - 408);
    [self.searchTableView removeFromSuperview];
}

- (void)localButtonAction{
    [self locateAction];
}

//  高德地图 隐私政策合规 地图实例化之前 加载

- (void)kGDYSHG{

    //地图
//
//    [MAMapView updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];
//    [MAMapView updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];



}

- (instancetype)initWithViewController:(UIViewController *)viewController {
    self = [super init];
    if (self) {
        self.controller = viewController;
    }
    return self;
}

@end

